from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime
from django.core.paginator import Paginator
from common.models import Users
# Create your views here.
def index(request, pageindex):
    '''浏览信息'''
    list = Users.objects.all()

    p = Paginator(list, 2)
    pagelist = p.page(pageindex)
    pagenumber = p.page_range
    context = {"userslist": pagelist,
               "pagenumber": pagenumber}
    return render(request,"myadmin/users/index.html", context)

def add(request):
    '''加载添加页面'''
    return render(request,"myadmin/users/add.html")

def insert(request):
    '''执行添加'''
    try:
        ob = Users()
        ob.username = request.POST['username']
        ob.name = request.POST['name']
        #获取密码并md5
        import hashlib
        m = hashlib.md5() 
        m.update(bytes(request.POST['password'],encoding="utf8"))
        ob.password = m.hexdigest()
        ob.sex = request.POST['sex']
        ob.address = request.POST['address']
        ob.code = request.POST['code']
        ob.phone = request.POST['phone']
        ob.email = request.POST['email']
        ob.state = 1
        ob.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context={"info":"添加成功！"}
    except Exception as err:
        print(err)
        context={"info":"添加失败"}
    return render(request,"myadmin/info.html",context)

def delete(request,uid):
    '''删除信息'''
    try:
        ob = Users.objects.get(id=uid)
        ob.delete()
        context={"info":"删除成功！"}
    except Exception as err:
        print(err)
        context={"info":"删除失败"}
    return render(request,"myadmin/info.html",context)


def edit(request,uid):
    '''加载编辑信息页面'''
    try:
        ob = Users.objects.get(id=uid)
        context={"user":ob}
        return render(request,"myadmin/users/edit.html",context)
    except Exception as err:
        context={"info":"没有找到要修改的信息！"}
        return render(request,"myadmin/info.html",context)

def update(request,uid):
    '''执行编辑信息'''
    try:
        ob = Users.objects.get(id=uid)
        ob.name = request.POST['name']
        ob.sex = request.POST['sex']
        ob.address = request.POST['address']
        ob.code = request.POST['code']
        ob.phone = request.POST['phone']
        ob.email = request.POST['email']
        ob.state = request.POST['state']
        ob.save()
        context={"info":"修改成功！"}
    except Exception as err:
        print(err)
        context={"info":"修改失败"}
    return render(request,"myadmin/info.html",context)

def editpassword(request, uid):
    '''加载修改密码页面'''
    try:
        ob = Users.objects.get(id=uid)
        context = {'user': ob}
        return render(request, 'myadmin/users/resetpassword.html', context)
    except Exception as error:
        context = {'info': '没有找到该用户'}
        return render(request, 'myadmin/info.html', context)

def resetpassword(request, uid):
    try:
        ob = Users.objects.get(id=uid)
        import hashlib
        m = hashlib.md5()
        m.update(bytes(request.POST['password'], encoding='utf8'))
        ob.password = m.hexdigest()
        ob.save()
        context = {'info': '密码重置成功'}
    except Exception as error:
        context = {'info': '没有找到该用户'}
    return render(request, 'myadmin/info.html', context)

def searchusers(request, pageindex):
    #先看有没有POST请求搜索关键字
    if request.POST.get('search', None):
        name = request.POST.get('search', None)
        print(name)
        context = handlesearch(request, name, pageindex)
        return render(request, 'myadmin/users/searchusers.html', context)
    elif 'search' in request.session:
        # 如果没有看session中有没有关键字
        name = request.session['search']
        context = handlesearch(request, name, pageindex)
        return render(request, 'myadmin/users/searchusers.html', context)
    else:
        # 如果仍然没有返回空白搜索页
        return render(request, 'myadmin/users/searchusers.html')


def handlesearch(request, name, pageindex):
    try:
        request.session['search'] = name
        ob = Users.objects.filter(name__contains=name)
        print(ob)
        p = Paginator(ob, 2)
        print(p)
        userlist = p.page(pageindex)
        pagenumber = p.page_range
        if len(userlist) == 0:
            context = {'userslist': userlist,
                       'pagenumber': pagenumber,
                       'state': 0}
        else:
            context = {'userslist': userlist,
                       'pagenumber': pagenumber,
                       'state': 1}

    except Exception as error:
        print(error)
        request.session['search'] = ''
        context = {'userslist': [],
                   'pagenumber': [],
                   'state': 0}
    return context


